import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import {
  Button,
  DatePicker,
  Form,
  Input,
  Modal,
  Radio,
  Tag,
  Select,
  InputNumber,
  message,
  Row,
  Col,
  Space,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request } from 'umi';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, } from '@ant-design/pro-components';
import { orderBy } from 'lodash';
const DictModal = (props: any, refs: any) => {
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();
  // const [fileList,setfileList] = useState([]);
  const [measureClassData, setmeasureClassData] = useState([]);
  const { setFieldsValue, resetFields } = form;

  const [code, setCode] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { TextArea } = Input;
  const requestsUrls = {
    list: "/sys/user/list",
    delete: "/sys/user/remove",
    deleteBatch: "/sys/dict/deleteBatch",
    exportXlsUrl: "/sys/dict/exportXls",
    importExcelUrl: "/sys/dict/importExcel",
  };
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };

  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setCode('');
    resetFields();
    props.callback && props.callback();
  };
  //确定
  const handleOk = () => {
    const url = `/sys/role/${code}/user`;
    request(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: measureClassData,
    }).then((res) => {
      message.success(res?.meta?.msg);
      setIsModalVisible(false);
      handleCancel();
    });
  };
  useImperativeHandle(refs, () => ({
    init: (roleId: any, list: any) => {
      setCode(roleId);
      let arr = list.map((item: any) => {
        return item.userId
      })
      setmeasureClassData(arr);
      showModal();
      // setfileList([]);
    },
  }));
  const columns: ProColumns<businessReportItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      title: '序号',
    },
    {
      title: '登录账号',
      key: 'user_code',
      dataIndex: 'user_code',
      hideInSearch: true,
    },

    {
      title: '用户名',
      key: 'user_name',
      dataIndex: 'user_name',
    },
    {
      title: '组织',
      key: 'org_name',
      dataIndex: 'org_name',
      hideInSearch: true,
    },
  ];
  return (
    <Modal
      title={code === '' ? '新增' : '编辑'}
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
      centered
      width={1000}
      maskClosable={false}
      bodyStyle={{
        maxHeight: window.innerHeight - 150,
        overflowY: 'auto',
      }}
    >
      <ProTable
        rowKey="user_id"
        rowSelection={{
          onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            setmeasureClassData(selectedRowKeys);
          },
          selectedRowKeys: measureClassData,
        }}
        actionRef={actionRef}
        columns={columns}
        options={false}
        search={false}
        params={form.getFieldsValue()}
        pagination={false}
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        request={async (
          // 第一个参数 params 查询表单和 params 参数的结合
          // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
          params: T & {
            pageSize: number;
            //current: number;
          },
          sort,
          filter,
        ) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const response: any = await request(requestsUrls.list, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            data: {
              ...params,
              ...{
                pageNo: params.current,
                pageSize: 100000,
                user_name: params.user_name,
              }
            },
          });
          return {
            data: response?.data?.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: true,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: response?.data?.totalCount,
            //message.success(res?.meta?.msg);
          };
        }}
      />
    </Modal>
  );
};
const AddMCom = forwardRef(DictModal);
export default AddMCom;
